<?php
/**
 * Function: 读写 接口服务端控制器
 * Description:
 * Abo 2019/1/21 20:58
 * Email: abo2013@foxmail.com
 */

namespace Abo\Fasterapi\V0\Controllers\Rwapi;

use Abo\Fasterapi\V0\Logics\Rwapi\RwServerLogic;
use Abo\Generalutil\V1\Utils\ResponseUtil;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class RwServerController extends Controller
{
    const MOBILE_AIDALAN_SALT = 'ad.aidalan.com_RwApi_Y6XQV4pa3k09';
    public $url_params, $request, $RwLogic;
    public static $table2Model = [
        'page_hour' => '\App\Models\AdData\PageHourModel',
    ];

    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->url_params = $request->all();

        if (!array_key_exists('sign', $this->url_params)
            || !array_key_exists('table', $this->url_params)
            || !array_key_exists($this->url_params[ 'table' ], self::$table2Model)
            || !array_key_exists('data', $this->url_params)
            || $this->url_params['sign'] != $this->getSign( $this->url_params['data'] )
        ) {
            return ResponseUtil::error()->message('Server busy...')->json();
        }

        $this->RwLogic = new RwServerLogic( self::$table2Model[ $this->url_params[ 'table' ] ] );
    }

    /** 直接 sql 查询 */
    public function query( Request $request )
    {
        $this->request = $request;
        $this->url_params = $request->all();

        if (!array_key_exists('sign', $this->url_params)
            || !array_key_exists('table', $this->url_params)
            || !array_key_exists($this->url_params[ 'table' ], self::$table2Model)
            || !array_key_exists('data', $this->url_params)
            || $this->url_params['sign'] != $this->getSign( $this->url_params['data'] )
        ) {
            return ResponseUtil::error()->message('Server busy...')->json();
        }

        $this->RwLogic = new RwServerLogic( self::$table2Model[ $this->url_params[ 'table' ] ] );

        try {
            $dataList = $this->RwLogic->sqlQuery( $this->url_params['data'][0] );

            return ResponseUtil::success()->paginate( $dataList['num'], 0 )->with( $dataList['data'] )->json();
        } catch (\Exception $e) {
            return ResponseUtil::error()->message( $e->getMessage() )->json();
        }
    }

    public function index(Request $request)
    {
        $this->request = $request;
        $this->url_params = $request->all();

        if (!array_key_exists('sign', $this->url_params)
            || !array_key_exists('table', $this->url_params)
            || !array_key_exists($this->url_params[ 'table' ], self::$table2Model)
            || !array_key_exists('data', $this->url_params)
            || $this->url_params['sign'] != $this->getSign( $this->url_params['data'] )
        ) {
            return ResponseUtil::error()->message('Server busy...')->json();
        }

        $this->RwLogic = new RwServerLogic( self::$table2Model[ $this->url_params[ 'table' ] ] );

        try {
            $dataList = $this->RwLogic->getList(
                $this->url_params['data'],
                $this->url_params['condition'],
                $this->url_params['page'],
                $this->url_params['pageSize'],
                (!array_key_exists( 'orderBy', $this->url_params ) ?:$this->url_params['orderBy']),
                (!array_key_exists( 'groupBy', $this->url_params ) ?:$this->url_params['groupBy'])
            );

            return ResponseUtil::success()->nums( $dataList[1] )->with( $dataList[0] )->json();
        } catch (\Exception $e) {
            return ResponseUtil::error()->message( $e->getMessage() )->json();
        }

    }

    /** todo 对保存数据 进行 数据库字段过滤 */
    public function add()
    {
        try {
            $ret2Add = $this->RwLogic->add( $this->url_params['data'] );

            return ResponseUtil::success()->with( $ret2Add )->json();
        } catch (\Exception $e) {
            return ResponseUtil::error()->message( $e->getMessage() )->json();
        }

    }

    public function save()
    {
        try {
            $ret2Add = $this->RwLogic->save( $this->url_params['id'], $this->url_params['data'] );

            return ResponseUtil::success()->with( $ret2Add )->json();
        } catch (\Exception $e) {
            return ResponseUtil::error()->message( $e->getMessage() )->json();
        }
    }

    public function del()
    {
        try {
            $ret2Add = $this->RwLogic->del( $this->url_params['id'], $this->url_params['column'] );

            return ResponseUtil::success()->with( $ret2Add )->json();
        } catch (\Exception $e) {
            return ResponseUtil::error()->message( $e->getMessage() )->json();
        }
    }

    public function refresh()
    {
        if ( !array_key_exists( 'key', $this->url_params ) || !$this->url_params['key'] ){ return false; }

        $redis = app('rediscache');
        $keys = $redis->keys( $this->url_params['key'].'*' );
        if ( !$keys ) { return false; }

        foreach ( $keys as $v2Key ) {
            $tem = $redis->del( $v2Key );
        }
    }

    /** 数据后台,盐值产生方法 @param array $data 请求参数 */
    protected function getSign( array $params )
    {
        ksort($params);
        $sign_str = '';
        foreach ($params as $key => $value) {
            $temValue = is_array( $value ) ? implode( ',', $value ) : $value;
            $sign_str .= $key . '=' . $temValue . '&';
        }

        $sign_str = substr($sign_str, 0, -1);
        $sign_str .= self::MOBILE_AIDALAN_SALT ?? '';
        $sign_str = md5($sign_str);
        return $sign_str;
    }
}